package com.guohui.boot1.running;

public class SimplePcm {

  private Integer product = 0;//商品数量
  
  
  public synchronized void produce() {
    if(product>=10) {
      try {
        System.out.println("库存量达到："+product+";开始售卖");
        notifyAll();
        if(product>=20) {
          System.out.println("库存量达到："+product+";停止生产");
          wait();
          return;
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    product++;
    System.out.println("库存数量："+product);
  }
  
  public synchronized void consumer() {
    if(product<=1) {
      try {
        System.out.println("库存数量不足。"+product+";停止售卖");
        notifyAll();
        wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      return;
    }
    product--;
    System.out.println("消费一次后产品数量:"+product);
  }
  
  
  public static void main(String[] args) {
    
    SimplePcm pcm = new SimplePcm();
    
    Thread t1 = new Thread(new Runnable() {
      @Override
      public void run() {
        while(true) {
          pcm.produce();
//          try {
//            Thread.sleep(300);
//          } catch (InterruptedException e) {
//            e.printStackTrace();
//          }
        }
      }
    });
    t1.start();
    
    Thread t2 = new Thread(new Runnable() {
      @Override
      public void run() {
        while(true) {
          pcm.consumer();
//          try {
//            Thread.sleep(10);
//          } catch (InterruptedException e) {
//            e.printStackTrace();
//          }
        }
      }
    });
    t2.start();
  }
}
